package com.cashg.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.BaseColumns;

public class CashGResponseHandler implements ResponseHandler {

	private RESTfulContentProvider cashGContentProvider;

	private String mQueryText;

	public CashGResponseHandler(RESTfulContentProvider restfulProvider,
			String queryText) throws IOException {
		cashGContentProvider = restfulProvider;
		mQueryText = queryText;

	}

	@Override
	public void handleResponse(HttpResponse response, Uri uri, Uri requestUri)
			throws IOException {
		
		int match = CashGContentProvider.sUriMatcher.match(requestUri);
		switch (match) {

		case CashGContentProvider.MERCHANT:
			if (response.getEntity() != null) {
				deleteOld(new CashGEntities.Merchant());
				insertMerchant(response);
				cashGContentProvider.getContext().getContentResolver().notifyChange(requestUri, null);
			}
		}
	}

	private void insertMerchant(HttpResponse response) {
		// get the json content
		String res = getStringContent(response.getEntity());
		if (res != null) {
			JSONArray obj;
			try {
				obj = new JSONArray(res);
		        for (int i = 0; i< obj.length(); i++) {
		        	JSONObject object = (JSONObject)obj.get(i);
		        	ContentValues  entry = new ContentValues();
		        	entry.put(CashGEntities.Merchant.NAME_COLUMN, object.getString(CashGEntities.Merchant.NAME_COLUMN));
		        	entry.put(CashGEntities.Merchant.THUMBNAIL, object.getString(CashGEntities.Merchant.THUMBNAIL));
		        	// Use same Content Uri to tell to Content provider to save this
		        	cashGContentProvider.insert(CashGEntities.Merchant.MERCHANT_URI, entry);
		        	
		        }
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	private String getStringContent(HttpEntity entity) {
		String inputLine = null;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					entity.getContent()));

			return in.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputLine;
	}
	
    private void deleteOld(ExpirableEntity entity) {
        // delete any old elements, not just ones that match the current query.

        Cursor old = null;

        try {
            SQLiteDatabase db = cashGContentProvider.getDatabase();
            old = db.query(entity.getTblName(), null,
                     entity.getExpirationTimeName() +
                            " < strftime('%s', 'now', '-" + entity.getFlushTime() + "')",
                    null, null, null, null);
            int c = old.getCount();
            if (old.getCount() > 0) {
                StringBuilder sb = new StringBuilder();
                boolean next;
                if (old.moveToNext()) {
                    do {
                        String ID = old.getString(entity.getIdColumnIndex());
                        sb.append(BaseColumns._ID);
                        sb.append(" = ");
                        sb.append(ID);

                        // get rid of associated cached thumb files
                        //mFinchVideoProvider.deleteFile(ID);

                        next = old.moveToNext();
                        if (next) {
                            sb.append(" OR ");
                        }
                    } while (next);
                }
                String where = sb.toString();

                db.delete(entity.getTblName(), where, null);

              //  Log.d(Finch.LOG_TAG, "flushed old query results: " + c);
            }
        } finally {
            if (old != null) {
                old.close();
            }
        }
    }

}
